import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ahj_app/app/yhpc/YhpcViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/bean/FileUpLoadBean.dart';
import 'package:flutter_ahj_app/base/bean/flutter_AMapLocation_map.dart';
import 'package:flutter_ahj_app/base/utils/HttpUtils.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/date_util.dart';
import 'package:flutter_ahj_app/base/utils/image_picked.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/SelectPicUtils.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../base/utils/video_player_page.dart';

class YhdjPageView extends BaseStatefulWidget {
  final String hazardId;
  YhdjPageView({this.hazardId});

  @override
  State<StatefulWidget> initState() {
    return YhdjPageViewState();
  }
}

class YhdjPageViewState extends BaseState<YhpcViewModel, YhdjPageView> {
  AMapLocation location;
  List _imageUrls = [];
  List _zgimageUrls = []; // 整改后的图片
  String _selDjlx = 'ssp';
  String _selYhdj = 'generalHazard';
  String _pcdxId = '';
  String _selOrgCode = '';
  String _selPersonOpenId = '';
  String _selRiskPointId = '';
  String _selDangerSourceId = '';
  String _selRiskDangerSourceEvaluateId = '';
  String _selHazardCategoryId = '';
  TextEditingController _pcdxCtr = TextEditingController(); // 排查对象
  TextEditingController _pcxCtr = TextEditingController(); // 排查项
  TextEditingController _pcnrCtr = TextEditingController(); // 排查内容
  TextEditingController _yhmcCtr = TextEditingController(); // 隐患名称
  TextEditingController _yhmsCtr = TextEditingController(); // 隐患描述
  TextEditingController _yhzrbmCtr = TextEditingController(); // 隐患责任部门
  TextEditingController _yhlbCtr = TextEditingController(); // 隐患类别
  TextEditingController _yhcsCtr = TextEditingController(); // 隐患场所
  TextEditingController _hcrCtr = TextEditingController(); // 核查人
  TextEditingController _yhdjCtr = TextEditingController(); // 隐患等级
  TextEditingController _yhzyCtr = TextEditingController(); // 隐患所属专业
  TextEditingController _yyfxCtr = TextEditingController(); // 简要原因分析
  TextEditingController _zglxCtr = TextEditingController(); // 整改类型
  TextEditingController _yhzgcsCtr = TextEditingController(); // 隐患整改措施
  TextEditingController _yhzgzrrCtr = TextEditingController(); // 隐患整改责任人
  TextEditingController _yhzgzrbmCtr = TextEditingController(); // 隐患整改责任部门
  TextEditingController _yhzgqkCtr = TextEditingController(); // 隐患整改情况
  TextEditingController _zgzjCtr = TextEditingController(); // 整改资金
  TextEditingController _zgwcsjCtr = TextEditingController(); // 整改完成时间

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _zgwcsjCtr.text = DateUtil.getDateStrByDateTime(
            DateTime.parse(DateTime.now().toString()),
            format: DateFormat.YEAR_MONTH_DAY_HOUR_MINUTE) +
        ':00';
    if (!StringUtils.isEmpty(widget.hazardId)) {
      _initData();
    }
  }

  String _hazardRegisterMethod = ""; //登记类型
  String _rectifyType = "";
  List _hazardRectifyBeforeFileList = [];
  List _hazardRectifyAfterFileList = [];
  _initData() {
    viewModel.yhzlListDetail(widget.hazardId);
    viewModel.yhzlListDetailStream().listen((event) {
      if (event['code'] == '0') {
        setState(() {
          var _dataM = event['data'];
          //登记类型
          _hazardRegisterMethod =
              StringUtils.getStr(_dataM['hazardRegisterMethod']);
          if (_hazardRegisterMethod == "snapshot") {
            _selDjlx = 'ssp';
            _selPersonOpenId =
                StringUtils.getStr(_dataM['deciderOpenId'].toString());
            _hcrCtr.text = StringUtils.getStr(_dataM['deciderName']);
          } else if (_hazardRegisterMethod == "register") {
            _selDjlx = 'dj';
            _selPersonOpenId =
                StringUtils.getStr(_dataM['verifierOpenId'].toString());
            _hcrCtr.text = StringUtils.getStr(_dataM['verifierName']);
          } else if (_hazardRegisterMethod == "rectifyRegister") {
            _selDjlx = 'xczgdj';
            _zgwcsjCtr.text = StringUtils.getStr(_dataM['rectifyCompleteTime']);
            _yhzyCtr.text = StringUtils.getStr(_dataM['hazardProfessionName']);
            _yhzgzrrCtr.text =
                StringUtils.getStr(_dataM['rectifyResponsiblePersonName']);
            _selPersonOpenId = StringUtils.getStr(
                _dataM['rectifyResponsiblePersonOpenId'].toString());
          }

          _pcdxCtr.text = StringUtils.getStr(_dataM['riskPointName']);
          _selRiskPointId =
              StringUtils.getStr(_dataM['riskPointId'].toString());
          _selDangerSourceId =
              StringUtils.getStr(_dataM['dangerSourceId'].toString());
          _selRiskDangerSourceEvaluateId = StringUtils.getStr(
              _dataM['riskDangerSourceEvaluateId'].toString());
          _pcnrCtr.text = StringUtils.getStr(_dataM['controlMeasure']);
          _selYhdj = StringUtils.getStr(_dataM['hazardRegisterLevel']);

          _yyfxCtr.text =
              StringUtils.getStr(_dataM['reasonAnalyzeDescription']);

          _pcxCtr.text = StringUtils.getStr(_dataM['dangerSourceName']);
          _yhmcCtr.text = StringUtils.getStr(_dataM['hazardName']);
          _yhlbCtr.text = StringUtils.getStr(_dataM['hazardCategoryName']);
          _yhmsCtr.text = StringUtils.getStr(_dataM['description']);
          _selHazardCategoryId =
              StringUtils.getStr(_dataM['hazardCategoryId'].toString());
          _yhzrbmCtr.text = StringUtils.getStr(_dataM['riskPointOrgCodeName']);

          _rectifyType = StringUtils.getStr(_dataM['rectifyType']);
          if (_rectifyType == "immediatelyRectify") {
            _zglxCtr.text = '立即整改';
          } else if (_rectifyType == "deadlineRectify") {
            _zglxCtr.text = '限期整改';
          } else if (_rectifyType == "stopBusinessRectify") {
            _zglxCtr.text = '停产';
          }

          _yhzgcsCtr.text = StringUtils.getStr(_dataM['rectifyMeasure']);
          _zgzjCtr.text = StringUtils.getStr(_dataM['rectifyMoney']);
          _selOrgCode = StringUtils.getStr(
              _dataM['rectifyResponsibleOrgCode'].toString());

          if (_dataM['hazardRectifyBeforeFileList'] != null) {
            _hazardRectifyBeforeFileList.clear();
            List _beforeList = _dataM['hazardRectifyBeforeFileList'];
            for (int i = 0; i < _beforeList.length; i++) {
              Map _map1 = {
                'fileName': _beforeList[i]['fileName'],
                'url': _beforeList[i]['url'],
              };
              _hazardRectifyBeforeFileList.add(_map1);
            }
            _imageUrls = _beforeList;

            print("读取首次返回的数量-----------${_beforeList.length}");
          }

          if (_dataM['hazardRectifyAfterFileList'] != null) {
            _hazardRectifyAfterFileList.clear();
            List _afterList = _dataM['hazardRectifyAfterFileList'];
            for (int i = 0; i < _afterList.length; i++) {
              Map _map2 = {
                'fileName': _afterList[i]['fileName'],
                'url': _afterList[i]['url'],
              };
              _hazardRectifyAfterFileList.add(_map2);
            }
            _zgimageUrls = _afterList;

            print("读取首次返回的数量-----------${_afterList.length}");
          }
        });
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }

  @override
  Widget initWidget() {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      backgroundColor: Color(0xfff4f5f6),
      appBar: MTopBar(
        elevation: 0,
        title: '隐患登记',
      ).create(),
      bottomSheet: BottomAppBar(),
      body: _bodyView(),
    );
  }

  _bodyView() {
    return Container(
      child: Column(
        children: [
          Expanded(
            child: Container(
              margin: EdgeInsets.all(15),
              decoration: BoxDecoration(
                  borderRadius: new BorderRadius.all(Radius.circular(6.0)),
                  color: SQColor.white),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
                      child: Column(
                        children: [
                          Container(
                            child: Row(
                              children: [
                                JText(
                                  '* ',
                                  color: SQColor.red,
                                ),
                                Container(
                                  child: JText('整改前隐患视图'),
                                ),
                              ],
                            ),
                          ),
                          buildImagePicked(context, true),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
                      child: Column(
                        children: [
                          Container(
                            child: Row(
                              children: [
                                JText(
                                  '* ',
                                  color: SQColor.red,
                                ),
                                Container(
                                  child: JText('登记类型'),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 10),
                            child: Row(
                              children: [
                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        _selDjlx = 'ssp';
                                        _selYhdj = 'generalHazard';
                                      });
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.only(right: 5),
                                      height: 35,
                                      decoration: BoxDecoration(
                                          color: _selDjlx == 'ssp'
                                              ? SQColor.theme_color
                                              : SQColor.white,
                                          border: Border.all(
                                            width: 1,
                                            color: SQColor.theme_color,
                                          ),
                                          borderRadius:
                                              BorderRadius.circular(8)),
                                      child: JText('随手拍',
                                          color: _selDjlx == 'ssp'
                                              ? SQColor.white
                                              : SQColor.theme_color,
                                          fontSize: 14),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        _selDjlx = 'dj';
                                        _selYhdj = 'generalHazard';
                                      });
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.only(right: 5),
                                      height: 35,
                                      decoration: BoxDecoration(
                                          color: _selDjlx == 'dj'
                                              ? SQColor.theme_color
                                              : SQColor.white,
                                          border: Border.all(
                                            width: 1,
                                            color: SQColor.theme_color,
                                          ),
                                          borderRadius:
                                              BorderRadius.circular(8)),
                                      child: JText('登记',
                                          color: _selDjlx == 'dj'
                                              ? SQColor.white
                                              : SQColor.theme_color,
                                          fontSize: 14),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        _selDjlx = 'xczgdj';
                                        _selYhdj = 'generalHazard';
                                      });
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.only(right: 5),
                                      height: 35,
                                      decoration: BoxDecoration(
                                          color: _selDjlx == 'xczgdj'
                                              ? SQColor.theme_color
                                              : SQColor.white,
                                          border: Border.all(
                                            width: 1,
                                            color: SQColor.theme_color,
                                          ),
                                          borderRadius:
                                              BorderRadius.circular(8)),
                                      child: JText('现场整改登记',
                                          color: _selDjlx == 'xczgdj'
                                              ? SQColor.white
                                              : SQColor.theme_color,
                                          fontSize: 14),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    _commField(
                        isMust: _selDjlx == 'ssp' ? false : true,
                        title: '排查对象',
                        controller: _pcdxCtr,
                        hintText: '请选择排查对象',
                        isReadOnly: true,
                        suffixIcon: Icon(
                          Icons.arrow_forward_ios_outlined,
                          size: Dimens.dimens15,
                          color: SQColor.black_999999,
                        ),
                        onTap: () {
                          Navigator.pushNamed(context, '/ChoosePcdxView')
                              .then((value) {
                            if (value != null) {
                              Map map = value;
                              _pcdxId = map['id'].toString();
                              _pcdxCtr.text = map['riskPointName'];
                              if (_selDjlx != 'xczgdj') {
                                _yhzrbmCtr.text = map['orgName'];
                              }
                              _yhcsCtr.text = map['districtName'];
                              _selRiskPointId = map['id'].toString();

                              _pcxCtr.text = '';
                              _selDangerSourceId = '';
                              _selRiskDangerSourceEvaluateId = '';
                              _pcnrCtr.text = '';
                            }
                          });
                        }),
                    _commField(
                        isMust: _selDjlx == 'ssp' ? false : true,
                        title: '排查项',
                        hintText: '请选择排查项',
                        controller: _pcxCtr,
                        isReadOnly: true,
                        suffixIcon: Icon(
                          Icons.arrow_forward_ios_outlined,
                          size: Dimens.dimens15,
                          color: SQColor.black_999999,
                        ),
                        onTap: () {
                          if (_pcdxCtr.text.isEmpty) {
                            ToastUtils.showToast('请先选择排查对象');
                            return;
                          }
                          Navigator.pushNamed(context, '/ChoosePcxView',
                                  arguments: _pcdxId)
                              .then((value) {
                            if (value != null) {
                              Map map = value;
                              _pcxCtr.text = map['dangerSourceName'];
                              _selDangerSourceId =
                                  map['dangerSourceId'].toString();
                              _selRiskDangerSourceEvaluateId =
                                  map['riskDangerSourceEvaluateId'].toString();
                              _pcnrCtr.text = map['controlMeasureList'][0];
                            }
                          });
                        }),
                    _commField(
                        isMust: _selDjlx == 'ssp' ? false : true,
                        title: '排查内容',
                        controller: _pcnrCtr,
                        hintText: '请选择排查内容',
                        isReadOnly: true,
                        onTap: () {
                          if (_pcnrCtr.text.isEmpty) {
                            ToastUtils.showToast('请先选择排查项');
                          }
                        }),
                    _commField(
                      isMust: true,
                      controller: _yhmcCtr,
                      title: '隐患名称',
                      hintText: '请输入隐患名称',
                    ),
                    _commField(
                      controller: _yhmsCtr,
                      title: '隐患描述',
                      hintText: '请输入隐患描述',
                      maxLength: 200,
                    ),
                    _commField(
                        isMust: false,
                        title: '隐患责任部门',
                        hintText: '请先选择排查对象',
                        isReadOnly: true,
                        controller: _yhzrbmCtr),
                    _commField(
                        isMust: _selDjlx == 'ssp' ? false : true,
                        title: '隐患类别',
                        hintText: '请选择隐患类别',
                        isReadOnly: true,
                        controller: _yhlbCtr,
                        suffixIcon: Icon(
                          Icons.arrow_forward_ios_outlined,
                          size: Dimens.dimens15,
                          color: SQColor.black_999999,
                        ),
                        onTap: () {
                          Navigator.pushNamed(context, '/ChooseYhlbView')
                              .then((value) {
                            if (value != null) {
                              Map map = value;
                              _selHazardCategoryId = map['id'].toString();
                              _yhlbCtr.text = map['category'];
                            }
                          });
                        }),
                    _selDjlx == 'xczgdj'
                        ? _commField(
                            title: '隐患等级',
                            isReadOnly: true,
                            controller: _yhdjCtr,
                            hintText: '一般隐患',
                          )
                        : Container(
                            margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
                            child: Column(
                              children: [
                                Container(
                                  child: Row(
                                    children: [
                                      JText(
                                        '* ',
                                        color: SQColor.red,
                                      ),
                                      Container(
                                        child: JText('隐患等级'),
                                      ),
                                    ],
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 10),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        child: InkWell(
                                          onTap: () {
                                            setState(() {
                                              _selYhdj = 'generalHazard';
                                            });
                                          },
                                          child: Container(
                                            alignment: Alignment.center,
                                            margin: EdgeInsets.only(right: 5),
                                            height: 35,
                                            decoration: BoxDecoration(
                                                color:
                                                    _selYhdj == 'generalHazard'
                                                        ? SQColor.theme_color
                                                        : SQColor.white,
                                                border: Border.all(
                                                  width: 1,
                                                  color: SQColor.theme_color,
                                                ),
                                                borderRadius:
                                                    BorderRadius.circular(8)),
                                            child: JText('一般隐患',
                                                color:
                                                    _selYhdj == 'generalHazard'
                                                        ? SQColor.white
                                                        : SQColor.theme_color,
                                                fontSize: 14),
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: InkWell(
                                          onTap: () {
                                            setState(() {
                                              _selYhdj = 'majorHazard';
                                            });
                                          },
                                          child: Container(
                                            alignment: Alignment.center,
                                            margin: EdgeInsets.only(right: 5),
                                            height: 35,
                                            decoration: BoxDecoration(
                                                color: _selYhdj == 'majorHazard'
                                                    ? SQColor.theme_color
                                                    : SQColor.white,
                                                border: Border.all(
                                                  width: 1,
                                                  color: SQColor.theme_color,
                                                ),
                                                borderRadius:
                                                    BorderRadius.circular(8)),
                                            child: JText('重大隐患',
                                                color: _selYhdj == 'majorHazard'
                                                    ? SQColor.white
                                                    : SQColor.theme_color,
                                                fontSize: 14),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                    _commField(
                        isMust: false,
                        title: '隐患所在场所/位置',
                        hintText: '请先选择排查对象',
                        isReadOnly: true,
                        controller: _yhcsCtr),
                    _selDjlx == 'xczgdj'
                        ? _xczgdjView()
                        : _commField(
                            isMust: true,
                            title: _selDjlx == 'ssp' ? '判定人' : '核查人',
                            hintText: _selDjlx == 'ssp' ? '请选择判定人' : '请选择核查人',
                            controller: _hcrCtr,
                            isReadOnly: true,
                            suffixIcon: Icon(
                              Icons.arrow_forward_ios_outlined,
                              size: Dimens.dimens15,
                              color: SQColor.black_999999,
                            ),
                            onTap: () {
                              Navigator.pushNamed(context, '/ChoosePersonDan',
                                      arguments: "")
                                  .then((value) {
                                if (value != null) {
                                  Map map = value;
                                  _selPersonOpenId = map['openId'];
                                  _hcrCtr.text = map['name'];
                                }
                              });
                            }),
                    Container(
                      height: 20,
                    ),
                  ],
                ),
              ),
            ),
          ),
          _bottomView()
        ],
      ),
    );
  }

  _xczgdjView() {
    return Column(
      children: [
        _commField(
          title: '隐患所属专业',
          hintText: '请输入隐患所属专业',
          controller: _yhzyCtr,
        ),
        _commField(
            title: '简要原因分析',
            hintText: '请输入简要原因分析',
            maxLength: 500,
            controller: _yyfxCtr),
        Container(
          margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
          child: Column(
            children: [
              Container(
                child: Row(
                  children: [
                    JText(
                      '* ',
                      color: SQColor.red,
                    ),
                    Container(
                      child: JText('整改后的隐患视图'),
                    ),
                  ],
                ),
              ),
              buildImagePicked(context, false),
            ],
          ),
        ),
        _commField(
          title: '整改类型',
          hintText: '立即整改',
          isReadOnly: true,
          controller: _zglxCtr,
          // suffixIcon: Icon(
          //   Icons.arrow_forward_ios_outlined,
          //   size: Dimens.dimens15,
          //   color: SQColor.black_999999,
          // ),
          // onTap: () {
          // Navigator.pushNamed(context, '/ChooseZglxView').then((value) {
          //   if (value != null) {
          //     _zglxCtr.text = value;
          //   }
          // });
          // }
        ),
        _commField(
          isMust: true,
          controller: _yhzgcsCtr,
          title: '隐患整改措施',
          hintText: '请输入隐患整改措施',
          maxLength: 500,
        ),
        _commField(
            isMust: true,
            title: '隐患整改部门',
            controller: _yhzrbmCtr,
            isReadOnly: true,
            hintText: '请选择隐患整改部门',
            onTap: () {
              Navigator.pushNamed(context, '/ChooseBuMen').then((value) {
                if (value != null) {
                  Map map1 = value;
                  _selOrgCode = map1['orgCode'];
                  _yhzgzrrCtr.text = '';
                  _yhzrbmCtr.text = value == null ? '' : map1['orgName'];
                }
              });
            }),
        _commField(
            isMust: true,
            title: '隐患整改责任人',
            controller: _yhzgzrrCtr,
            isReadOnly: true,
            hintText: '请选择隐患整改责任人',
            onTap: () {
              if (_selOrgCode.isEmpty) {
                ToastUtils.showToast('请先选择整改部门');
                return;
              }
              Navigator.pushNamed(context, '/ChoosePersonDan',
                      arguments: _selOrgCode)
                  .then((value) {
                if (value != null) {
                  Map map = value;
                  _selPersonOpenId = map['openId'];
                  _yhzgzrrCtr.text = map['name'];
                }
              });
            }),
        _commField(
            title: '隐患整改情况',
            hintText: '请输入隐患整改情况',
            maxLength: 500,
            controller: _yhzgqkCtr),
        _commField(
          title: '隐患整改资金（元）',
          controller: _zgzjCtr,
          hintText: '请输入隐患整改资金（元）',
          inputFormatters: [
            LengthLimitingTextInputFormatter(8),
            FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
          ],
        ),
        _commField(
          title: '整改完成时间',
          isReadOnly: true,
          controller: _zgwcsjCtr,
          hintText: '默认当前时间',
        ),
      ],
    );
  }

  int _maxCount = 6;
  Widget buildImagePicked(BuildContext context, bool isBefore) {
    return new Container(
        padding: const EdgeInsets.all(10.0),
        child: GridView.builder(
            padding: EdgeInsets.zero,
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4, //每行三列
                childAspectRatio: 1.0 //显示区域宽高相等
                ),
            itemCount: isBefore
                ? _imageUrls.length == 0
                    ? 1
                    : (_imageUrls.length == _maxCount
                        ? _imageUrls.length
                        : _imageUrls.length + 1)
                : _zgimageUrls.length == 0
                    ? 1
                    : (_zgimageUrls.length == _maxCount
                        ? _zgimageUrls.length
                        : _zgimageUrls.length + 1),
            itemBuilder: (context, index) {
              return _item(index, isBefore);
            }));
  }

  _item(int index, bool isBefore) {
    List imgs = isBefore ? _imageUrls : _zgimageUrls;
    return new GestureDetector(
      onTap: () {
        if (index != imgs.length) {
          if (imgs[index]['url'].contains("mp4")) {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => VideoPlayerPage(
                          videoPath: imgs[index]['url'],
                          videoSource: "1",
                        )));
          } else {
            List<String> filePath = [];
            int position = 0;
            for (int i = 0; i < imgs.length; i++) {
              if (!imgs[i]['url'].contains(".mp4")) {
                filePath.add(imgs[i]['url']);
              }
            }
            for (int i = 0; i < filePath.length; i++) {
              if (filePath[i] == imgs[index]) {
                position = i;
              }
            }
            Navigator.pushNamed(context, "/ShowImage",
                arguments: {'position': position, 'filePath': filePath});
          }
        } else {
          _pickImage(isBefore);
        }
      },
      child: index != imgs.length
          ? Container(
              margin: EdgeInsets.only(right: 5, bottom: 5),
              child: ImagePicked(
                      key: UniqueKey(),
                      imageUrl: imgs[index]['url'],
                      closeState: "0",
                      index: index,
                      boxFit: BoxFit.cover,
                      valueChanged: (index) {
                        setState(() {
                          imgs.removeAt(index);
                          if (isBefore &&
                              _hazardRectifyBeforeFileList.length > 0) {
                            _hazardRectifyBeforeFileList.removeAt(index);
                          }
                          if (!isBefore &&
                              _hazardRectifyAfterFileList.length > 0) {
                            _hazardRectifyAfterFileList.removeAt(index);
                          }
                        });
                      },
                    ),
            )
          : new Container(
              color: Theme.of(context).dividerColor,
              width:
                  (MediaQuery.of(context).size.width - 32.0 - 8.0) / _maxCount,
              height:
                  (MediaQuery.of(context).size.width - 32.0 - 8.0) / _maxCount,
              child: new Icon(
                Icons.add,
                size: 20.0,
                color: Colors.grey,
              ),
            ),
    );
  }

  bool showing = false;
  //多图选择器
  _pickImage(bool isBefore) async {
    showing = true;
    showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return new SimpleDialog(
          title: new Text('*选择附件(隐患视图)'),
          children: <Widget>[
            new SimpleDialogOption(
              child: new InkWell(
                child: new Container(
                  child: new Text(
                    '照相',
                    style: new TextStyle(fontSize: 16),
                  ),
                  height: 48,
                  alignment: Alignment.centerLeft,
                ),
              ),
              onPressed: () {
                onSelectPicClick("0", isBefore);
                Navigator.of(context).pop(true);
                showing = false;
              },
            ),
            new SimpleDialogOption(
              child: new InkWell(
                child: new Container(
                  child: new Text(
                    '从相册选择',
                    style: new TextStyle(fontSize: 16),
                  ),
                  height: 48,
                  alignment: Alignment.centerLeft,
                ),
              ),
              onPressed: () {
                onSelectPicClick("1", isBefore);
                Navigator.of(context).pop(true);
                showing = false;
              },
            ),
            new SimpleDialogOption(
              child: new InkWell(
                child: new Container(
                  child: new Text(
                    '视频录制',
                    style: new TextStyle(fontSize: 16),
                  ),
                  height: 48,
                  alignment: Alignment.centerLeft,
                ),
              ),
              onPressed: () {
                onSelectPicClick("2", isBefore);
                Navigator.of(context).pop(true);
                showing = false;
              },
            ),
          ],
        );
      },
    );
  }

  void onSelectPicClick(String type, bool isBefore) async {
    List imgs = isBefore ? _imageUrls : _zgimageUrls;
    List result;
    Map<String, String> map = {
      "count": (_maxCount - imgs.length).toString(),
      "adress": location == null ? "暂无获取定位信息" : location.locationDescribe
    };
    if ("0" == type) {
      //照相
      if (location == null) {
        String resultStr =
            await PerUtils.checkPermission(context, [Permission.location]);
        if (resultStr == '1') {
          location = await FlutterAMapLocation.getCurrentLocation();
          if (location == null) {
            ToastUtils.showToast("获取位置信息失败，暂不能拍照");
          } else {
            map["adress"] = location.locationDescribe;
            String resultStr =
                await PerUtils.checkPermission(context, [Permission.camera]);
            if (resultStr == '1') {
              result = await SelectPicUtils.getTakePic(map);
            }
          }
        } else {
          ToastUtils.showToast("获取位置信息失败，暂不能拍照");
        }
      } else {
        String resultStr =
            await PerUtils.checkPermission(context, [Permission.camera]);
        if (resultStr == '1') {
          result = await SelectPicUtils.getTakePic(map);
        }
      }
      //照相
    } else if ("1" == type) {
      //选择图片
      result = await SelectPicUtils.getSelectPic(map);
    } else if ("2" == type) {
      var microphoneStatus = await Permission.microphone.request();
      var cameraStatus = await Permission.camera.request();
      var storageStatus = await Permission.storage.request();

// String resultStr = await PerUtils.checkPermission(
//     context, [Permission.speech, Permission.camera, Permission.microphone]);

      if (cameraStatus == PermissionStatus.granted && microphoneStatus == PermissionStatus.granted && storageStatus == PermissionStatus.granted) {
        // 权限被授予，可以拍摄视频
        result = await SelectPicUtils.getSelectVideo(map);
      }else {
        ToastUtils.showToast("请先获取相机/录音等权限");
        return;
      }
    }
    setState(() {
      result.forEach((f) {
        Map map = {
          'fileName': '本地',
          'url': f,
        };
        imgs.add(map);
      });
    });
    isBefore ? _upLoadImage() : _zgUploadImage();
  }

  _bottomView() {
    return Row(
      children: [
        Expanded(
          child: InkWell(
            onTap: () {
              _done(true);
            },
            child: SafeArea(
              child: Container(
                margin: EdgeInsets.only(left: 15, right: 15, bottom: 15),
                height: 45,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: SQColor.white,
                    border: Border.all(
                      width: 1,
                      color: SQColor.theme_color,
                    ),
                    borderRadius: BorderRadius.circular(8)),
                child: JText('保存', color: SQColor.theme_color),
              ),
            ),
          ),
        ),
        Expanded(
          child: InkWell(
            onTap: () {
              _done(false);
            },
            child: SafeArea(
              child: Container(
                margin: EdgeInsets.only(left: 15, right: 15, bottom: 15),
                height: 45,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: SQColor.theme_color,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: JText('提交', color: Colors.white),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 提交保存
  _done(bool isSave) {
    if (_imageUrls.length == 0) {
      ToastUtils.showToast('请选择整改前隐患视图');
      return;
    }
    if (_yhmcCtr.text.isEmpty) {
      ToastUtils.showToast('请填写隐患名称');
      return;
    }
    if (_selDjlx == 'ssp') {
      if (_hcrCtr.text.isEmpty) {
        ToastUtils.showToast('请选择判定人');
        return;
      }
    } else if (_selDjlx == 'dj') {
      if (_pcdxCtr.text.isEmpty) {
        ToastUtils.showToast('请选择排查对象');
        return;
      }
      if (_pcxCtr.text.isEmpty) {
        ToastUtils.showToast('请选择排查项');
        return;
      }
      if (_pcnrCtr.text.isEmpty) {
        ToastUtils.showToast('请选择排查内容');
        return;
      }
      if (_yhlbCtr.text.isEmpty) {
        ToastUtils.showToast('请选择排查类别');
        return;
      }
      if (_hcrCtr.text.isEmpty) {
        ToastUtils.showToast('请选择核查人');
        return;
      }
    } else if (_selDjlx == 'xczgdj') {
      if (_pcdxCtr.text.isEmpty) {
        ToastUtils.showToast('请选择排查对象');
        return;
      }
      if (_pcxCtr.text.isEmpty) {
        ToastUtils.showToast('请选择排查项');
        return;
      }
      if (_pcnrCtr.text.isEmpty) {
        ToastUtils.showToast('请选择排查内容');
        return;
      }
      if (_zgimageUrls.length == 0) {
        ToastUtils.showToast('请选择整改后隐患视图');
        return;
      }
      if (_yhzgzrrCtr.text.isEmpty) {
        ToastUtils.showToast('请选择隐患整改责任人');
        return;
      }
    }
    _submit(isSave);
  }

  _upLoadImage() {
    List<String> _uploadimageUrls = [];
    _hazardRectifyBeforeFileList.clear();
    for (var i = 0; i < _imageUrls.length; i++) {
      if (_imageUrls[i]['fileName'] == '本地') {
        _uploadimageUrls.add(_imageUrls[i]['url']);
      } else {
        _hazardRectifyBeforeFileList.add(_imageUrls[i]);
      }
    }

    HttpUtils.httpUpLoadPost(
        HttpBaseConst.serverUrl + HttpBaseConst.UPLOAD, _uploadimageUrls,
        (data) {
      setState(() {
        FileUpLoadBean fileUpLoadBean =
            FileUpLoadBean.fromJson(json.decode(data));

        for (int i = 0; i < fileUpLoadBean.data.length; i++) {
          Map map = {
            'fileName': fileUpLoadBean.data[i].fileName,
            'url': fileUpLoadBean.data[i].urlPath,
          };
          _hazardRectifyBeforeFileList.add(map);
        }
        print(_hazardRectifyBeforeFileList.length);
        print("整改前图片数量---------");
      });
    }, context: context);
  }

  _zgUploadImage() {
    List<String> _uploadimageUrls1 = [];
    _hazardRectifyAfterFileList.clear();
    for (var i = 0; i < _imageUrls.length; i++) {
      if (_imageUrls[i]['fileName'] == '本地') {
        _uploadimageUrls1.add(_imageUrls[i]['url']);
      } else {
        _hazardRectifyAfterFileList.add(_imageUrls[i]);
      }
    }

    HttpUtils.httpUpLoadPost(
        HttpBaseConst.serverUrl + HttpBaseConst.UPLOAD, _uploadimageUrls1,
        (data) {
      setState(() {
        FileUpLoadBean fileUpLoadBean1 =
            FileUpLoadBean.fromJson(json.decode(data));
        for (int i = 0; i < fileUpLoadBean1.data.length; i++) {
          Map map2 = {
            'fileName': fileUpLoadBean1.data[i].fileName,
            'url': fileUpLoadBean1.data[i].urlPath,
          };
          _hazardRectifyAfterFileList.add(map2);
        }
        print(_hazardRectifyAfterFileList.length);
        print("整改后图片数量---------");
      });
    }, context: context);
  }

  _submit(bool isSave) {
    var map = {
      'id': widget.hazardId,
      'riskPointId': _selRiskPointId,
      'dangerSourceId': _selDangerSourceId,
      'riskDangerSourceEvaluateId': _selRiskDangerSourceEvaluateId,
      'controlMeasure': _pcnrCtr.text,
      'hazardRegisterLevel': _selYhdj,
      'hazardRegisterMethod': _selDjlx == 'ssp'
          ? 'snapshot'
          : _selDjlx == 'dj'
              ? 'register'
              : 'rectifyRegister',
      'reasonAnalyzeDescription': _yyfxCtr.text,
      'hazardName': _yhmcCtr.text,
      'description': _yhmsCtr.text,
      'hazardCategoryId': _selHazardCategoryId,
      'hazardRectifyBeforeFileList': _hazardRectifyBeforeFileList,
      'deciderOpenId': _selDjlx == 'ssp' ? _selPersonOpenId : null,
      'verifierOpenId': _selDjlx == 'dj' ? _selPersonOpenId : null,
      'hazardProfessionName': _selDjlx == 'xczgdj' ? _yhzyCtr.text : null,
      'hazardRectifyAfterFileList':
          _selDjlx == 'xczgdj' ? _hazardRectifyAfterFileList : [],
      'rectifyType': _selDjlx == 'xczgdj' ? 'immediatelyRectify' : null,
      'rectifyMeasure': _selDjlx == 'xczgdj' ? _yhzgcsCtr.text : null,
      'rectifyMoney': _selDjlx == 'xczgdj' ? _zgzjCtr.text : null,
      'rectifyCompleteTime': _selDjlx == 'xczgdj' ? _zgwcsjCtr.text : null,
      'rectifyResponsiblePersonOpenId':
          _selDjlx == 'xczgdj' ? _selPersonOpenId : null,
      'rectifyResponsibleOrgCode': _selDjlx == 'xczgdj' ? _selOrgCode : null,
      'saveOrSubmit': isSave ? 'save' : 'submit'
    };
    ToastUtils.showLoading();
    viewModel.yhdj(map);
    viewModel.yhdjDataStream().listen((event) {
      ToastUtils.dissLoading();
      if (event['code'] == '0') {
        ToastUtils.showToast('登记成功');
        Navigator.pop(context);
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      ToastUtils.dissLoading();
      print(e);
    });
  }

  _commField(
      {bool isMust = false,
      String hintText = '',
      Widget suffixIcon,
      String title = '',
      bool isReadOnly = false,
      int maxLength,
      var onTap,
      var controller,
      var inputFormatters}) {
    return Container(
      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
      child: Column(
        children: [
          Container(
            child: Row(
              children: [
                isMust
                    ? JText(
                        '* ',
                        color: SQColor.red,
                      )
                    : Container(),
                Container(
                  child: JText(title),
                ),
              ],
            ),
          ),
          Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 10),
            padding: EdgeInsets.only(
                left: 10,
                right: maxLength == null ? 0 : 10,
                bottom: maxLength == null ? 0 : 10),
            child: TextField(
              controller: controller,
              inputFormatters: inputFormatters,
              onTap: onTap,
              maxLength: maxLength,
              readOnly: isReadOnly,
              style: TextStyle(fontSize: Dimens.textSize28),
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: hintText,
                  hintStyle: TextStyle(fontSize: Dimens.textSize28),
                  suffixIcon: suffixIcon),
            ),
            decoration: BoxDecoration(
              border: Border.all(
                width: 1,
                color: SQColor.lineE7E7E7,
              ),
              borderRadius: BorderRadius.all(Radius.circular(Dimens.dimens4)),
            ),
          ),
        ],
      ),
    );
  }
}
